package operation;

import Medicine.Pharmacy;
import org.apache.commons.dbutils.QueryRunner;
import JDBC.*;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
//添加药品
public class AddMedicine implements IOPeration{
    @Override
    public void work(Pharmacy pharmacy) throws SQLException {
        //创建QueryRunner对象
        QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

        System.out.println(" 添加入库药品 ");
        Scanner sc = new Scanner(System.in);

        System.out.println(" 请输入编号:");
        int id = sc.nextInt();
        System.out.println("请输入您想入库的药品名称:");
        String name = sc.next();
        sc.nextLine();

        String query = "SELECT name FROM medicine";
        List<Map<String, Object>> medicineList = qr.query(query, new MapListHandler());
        for (Map<String, Object> medicineMap : medicineList) {
            if (medicineMap.get("name").equals(name)) {
                System.out.println("这类药材已经入库，无需再添加");
                return;
            }
        }
        System.out.println("请输入该药品的类型: [中药] [西药] ");
        String type = sc.nextLine();
        if(!(type.equals("中药")||type.equals("西药"))){
            System.out.println("该药品类型的暂未收录,导致入库失败");
            return;
        }

        System.out.println("请输入该药品的价格:");
        int price = sc.nextInt();
        sc.nextLine();
        System.out.println("请输入入库药品的数量");
        int amount = sc.nextInt();
        System.out.println("请输入该药品的生产日期: ");
        String ManufactureDate = sc.next();
        sc.nextLine();
        System.out.println("请输入该药品的保质期");
        int bestDate = sc.nextInt();

        //定义插入药房的医疗器械
        String sql = "INSERT INTO medicine (Id,Name,Type,Price,Amount,ManufactureDate,BestDate)" +
                " VALUES(?,?,?,?,?,?,?)";
        //设置传入SQL中的参数值
        Object[] parms={id,name,type,price,amount,ManufactureDate,bestDate};
        //执行插入信息的SQL
        int count = qr.update(sql, parms);
        if(count<1){
            System.out.println("新增药品信息失败！");
        }else{
            System.out.println("新增药品信息成功！");
        }

    }
}
